package zdream.control.foe.mm2shot;

import zdream.control.world.buff.AttackModule;
import zdream.control.world.buff.HealthModule;
import zdream.control.world.MFoe;
import zdream.control.world.MHookType;
import zdream.control.world.MHooks;
import zdream.control.world.TerrainHandler;
import zdream.control.world.Ticker;

import static zdream.control.world.MFoeConstants.*;

/**
 * @author Zdream
 * @since 0.0.1
 * @date 2022-06-05 (last modified)
 */
public class MM2ShotManBullet extends MFoe {
	public static final String NAME = "MM2ShotManBullet";
	public final MM2ShotMan owner;

	public MM2ShotManBullet(MM2ShotMan owner) {
		super(owner.world);
		this.owner = owner;
		this.type = TYPE_BULLET;
		this.side = owner.side;
	}

	@Override
	public String foeName() {
		return NAME;
	}

	@Override
	public void init() {
		createNormalPattern()
				.withRectangle(-1/6f, -1/6f, 1/3f, 1/3f)
				.apply();

		attackModule = buildAttackModule()
				.damage(2)
				.damageLevel(DAMAGE_LEVEL_BULLET)
				.ignoreSide(side)
				.targetTypesIsEntity()
				.stopAfterAttackOnce()
				.destroyAfterAttackReceived()
				.create();
		healthModule = buildHealthModule()
				.maxAgeInMS(3000)
				.create();

		terrainHandler = new TerrainHandler(world);
		terrainHandler.floating = true;

		onHook(MHookType.TICK)
				.handle(this::handleMotion)
				.buildAndSave();
	}
	public HealthModule healthModule;
	public AttackModule attackModule;

	/**
	 * 横向速度, 是个定值, 单位: p / 步
	 */
	public float vx;
	/**
	 * 纵向初始速度, 单位: p / 步
	 */
	public float initVy;
	/**
	 * 纵向加速度, 每步变化量, 单位: p / 步^2
	 */
	public float ay;
	/**
	 * 纵向最快速度, 正值. 纵向速度的绝对值不会大于它
	 */
	public float maxVy;

	/**
	 * 当前纵向速度
	 */
	public float vy;

	public MM2ShotManBullet set(float vx, float initVy, float ay, float maxVy) {
		this.vx = vx;
		this.initVy = initVy;
		this.ay = ay;
		this.maxVy = maxVy;

		vy = initVy;
		return this;
	}

	public void handleMotion(MHooks.MHookContext rawContext) {
		Ticker ticker = world.ticker;
		if (ticker.foePaused) {
			return;
		}

		vy += ay * ticker.duration;
		if (vy > maxVy) {
			vy = maxVy;
		} else if (vy < -maxVy) {
			vy = -maxVy;
		}

		setVelocity(vx * ticker.duration, vy * ticker.duration);
		terrainHandler.submitFloatBoxMotion(this);
	}
}
